package com.boot.blog.web.admin;

import com.boot.blog.po.User;
import com.boot.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * @创建人:yewei
 * @创建时间: 2019/12/1 20:58
 * @描述
 */
@Controller
@RequestMapping("/admin")
public class LoginController {
    @Autowired
    UserService userService;

    @RequestMapping("/adminindex")
    public String loginPage(){
        return "admin/index";
    }

    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes, Model model){
        User user = userService.checkUser(username, password);
        if (null != user) {
            user.setUsername(null);
            session.setAttribute("user",user);
            return "admin/index";
        }else {
            attributes.addFlashAttribute("message","用户名或密码错误");
            return "redirect:/admin/index";
        }
    }

    @GetMapping("/logut")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/admin";
    }
}
